﻿using log4net;
using McsUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MinerManager.Forms
{
	public partial class MinerWallet : Form
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;

		public event EventHandler<EventArgs> OnClose;

		private ContextMenuStrip RightContextMenu = null;
		private string ContextMenuSourceName = string.Empty;//点击ContextMenuStrip的来源控件名称
		private int SelectedCurrencyId = 0;//选中的币种Id
		
		public MinerWallet(Common.AgentComponent agent)
		{
			InitializeComponent();
			this.Agent = agent;
		}

		#region 窗体事件

		private void MinerWallet_Load(object sender, EventArgs e)
		{
			this.Agent.OnGetCurrencysReceive += new EventHandler<ByteEventArgs>(Agent_OnGetCurrencys);
			this.Agent.OnDeletePoolReceive += new EventHandler<ByteEventArgs>(Agent_OnDeletePoolReceive);
			this.Agent.OnDeleteWalletReceive += new EventHandler<ByteEventArgs>(Agent_OnDeleteWalletReceive);

			LoadContextMenu();
			AgentSendRefresh();
		}

		private void MinerWallet_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.Agent.OnGetCurrencysReceive -= new EventHandler<ByteEventArgs>(Agent_OnGetCurrencys);
			this.Agent.OnDeletePoolReceive -= new EventHandler<ByteEventArgs>(Agent_OnDeletePoolReceive);
			this.Agent.OnDeleteWalletReceive -= new EventHandler<ByteEventArgs>(Agent_OnDeleteWalletReceive);

			OnClose?.Invoke(this, new EventArgs());
		}

		private void LoadContextMenu()
		{
			this.RightContextMenu = new ContextMenuStrip();

			#region 修改事件

			Action<object, EventArgs> editClick = delegate (object obj, EventArgs args)
			{
				if(this.ContextMenuSourceName.Equals("WalletList", StringComparison.CurrentCultureIgnoreCase))
				{
					McsUtility.Models.WalletsModel info = (McsUtility.Models.WalletsModel)WalletList.SelectedItems[0].Tag;
					WalletUpdate form = new WalletUpdate(this.Agent, info);
					form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
					form.ShowDialog();
				}

				if(this.ContextMenuSourceName.Equals("PoolList", StringComparison.CurrentCultureIgnoreCase))
				{
					McsUtility.Models.WalletsModel info = (McsUtility.Models.WalletsModel)PoolList.SelectedItems[0].Tag;
					PoolUpdate form = new PoolUpdate(this.Agent, info);
					form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
					form.ShowDialog();
				}
			};

			ToolStripMenuItem itemEdit = new ToolStripMenuItem("修改");
			itemEdit.Click += new EventHandler(editClick);
			this.RightContextMenu.Items.Add(itemEdit);

			#endregion

			#region 删除事件

			Action<object, EventArgs> deleteClick = delegate (object obj, EventArgs args)
			{
				if (this.ContextMenuSourceName.Equals("WalletList", StringComparison.CurrentCultureIgnoreCase))
				{
					if (MessageBox.Show("确定要删除选择的钱包吗？\r\n删除后将不可恢复。", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
					{
						//发送数据
						if (this.Agent.IsStarted)
						{
							McsUtility.Models.WalletsModel info = (McsUtility.Models.WalletsModel)WalletList.SelectedItems[0].Tag;
							byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerDelWallets, info);
							this.Agent.AgentSend(bytes);
						}
						else
						{
							if (MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
								Common.Utility.FormClose(this);
						}
					}
				}

				if (this.ContextMenuSourceName.Equals("PoolList", StringComparison.CurrentCultureIgnoreCase))
				{
					if (MessageBox.Show("确定要删除选择的矿池吗？\r\n删除后将不可恢复。", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
					{
						//发送数据
						if (this.Agent.IsStarted)
						{
							McsUtility.Models.WalletsModel info = (McsUtility.Models.WalletsModel)PoolList.SelectedItems[0].Tag;
							byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerDelOrePools, info);
							this.Agent.AgentSend(bytes);
						}
						else
						{
							if (MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
								Common.Utility.FormClose(this);
						}
					}
				}
			};

			ToolStripMenuItem itemDelete = new ToolStripMenuItem("删除");
			itemDelete.Click += new EventHandler(deleteClick);
			this.RightContextMenu.Items.Add(itemDelete);

			#endregion
		}

		#endregion

		#region Agent事件

		private void Agent_OnGetCurrencys(object sender, ByteEventArgs e)
		{
			Common.Data.UserCurrency = ProtocolHelper.ReadPackageBody<List<McsUtility.Models.CurrencysModel>>(e.Bytes);
			RefreshList();
		}

		private void Agent_OnDeletePoolReceive(object sender, ByteEventArgs e)
		{
			McsUtility.Models.ResultModel result = ProtocolHelper.ReadPackageBody<McsUtility.Models.ResultModel>(e.Bytes);
			if (result.success)
				AgentSendRefresh();
			else
				MessageBox.Show("矿池删除失败，" + result.message + "。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		private void Agent_OnDeleteWalletReceive(object sender, ByteEventArgs e)
		{
			McsUtility.Models.ResultModel result = ProtocolHelper.ReadPackageBody<McsUtility.Models.ResultModel>(e.Bytes);
			if (result.success)
				AgentSendRefresh();
			else
				MessageBox.Show("钱包删除失败，" + result.message + "。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		#endregion

		#region TopMenu按钮点击事件

		private void TopMenu_WalletAdd_Click(object sender, EventArgs e)
		{
			WalletInsert form = new WalletInsert(this.Agent, this.SelectedCurrencyId);
			form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
			form.ShowDialog();
		}

		private void TopMenu_PoolAdd_Click(object sender, EventArgs e)
		{
			PoolInsert form = new PoolInsert(this.Agent, this.SelectedCurrencyId);
			form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
			form.ShowDialog();
		}

		private void TopMenu_Refresh_Click(object sender, EventArgs e)
		{
			AgentSendRefresh();
		}

		private void TopMenu_SyncLtcc_Click(object sender, EventArgs e)
		{
			Forms.MinerSyncLtcc form = new MinerSyncLtcc(this.Agent);
			form.OnSuccess += new EventHandler<EventArgs>(RefreshEventArgs);
			form.ShowDialog();
		}

		#endregion

		#region ListView的鼠标点击事件

		private void CurrencyList_MouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Right)
			{
				this.ContextMenuSourceName = "CurrencyList";
				this.RightContextMenu.Show(CurrencyList, e.Location);
			}
		}
		
		private void WalletList_MouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Right)
			{
				this.ContextMenuSourceName = "WalletList";
				this.RightContextMenu.Show(WalletList, e.Location);
			}
		}

		private void PoolList_MouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Right)
			{
				this.ContextMenuSourceName = "PoolList";
				this.RightContextMenu.Show(PoolList, e.Location);
			}
		}

		#endregion

		#region void CurrencyList_Click(object sender, EventArgs e)

		private void CurrencyList_Click(object sender, EventArgs e)
		{
			WalletList.Items.Clear();
			PoolList.Items.Clear();

			McsUtility.Models.CurrencysModel infoCurrency = (McsUtility.Models.CurrencysModel)CurrencyList.SelectedItems[0].Tag;
			SelectedCurrencyId = infoCurrency.ID;

			for (int j = 0; j < infoCurrency.Wallets.Count; j++)
			{
				McsUtility.Models.WalletsModel infoWallet = infoCurrency.Wallets[j];
				ListViewItem itemWallet = new ListViewItem(new string[] { (j + 1).ToString(), infoCurrency.Remark, infoWallet.Address, infoWallet.Remark })
				{
					Tag = infoWallet
				};
				WalletList.Items.Add(itemWallet);
			}

			for (int j = 0; j < infoCurrency.OrePools.Count; j++)
			{
				McsUtility.Models.WalletsModel infoPool = infoCurrency.OrePools[j];
				ListViewItem itemPool = new ListViewItem(new string[] { (j + 1).ToString(), infoCurrency.Remark, infoPool.Address, infoPool.Remark })
				{
					Tag = infoPool
				};
				PoolList.Items.Add(itemPool);
			}
		}

		#endregion



		#region void RefreshList() 刷新数据。

		private delegate void DelegeteRefresh();

		/// <summary>
		/// 刷新数据。
		/// </summary>
		private void RefreshList()
		{
			if (CurrencyList.InvokeRequired)
			{
				DelegeteRefresh d = new DelegeteRefresh(RefreshList);
				this.BeginInvoke(d);
			}
			else
			{
				CurrencyList.Items.Clear();
				WalletList.Items.Clear();
				PoolList.Items.Clear();

				int walletCount = 1;
				int poolCount = 1;
				for (int i = 0; i < Common.Data.UserCurrency.Count; i++)
				{
					McsUtility.Models.CurrencysModel infoCurrency = Common.Data.UserCurrency[i];
					ListViewItem itemCurrency = new ListViewItem(new string[] { (i + 1).ToString(), infoCurrency.Remark })
					{
						Tag = infoCurrency
					};
					itemCurrency.Selected = infoCurrency.ID == this.SelectedCurrencyId;
					CurrencyList.Items.Add(itemCurrency);

					if (this.SelectedCurrencyId == 0 || infoCurrency.ID == this.SelectedCurrencyId)
					{
						for (int j = 0; j < infoCurrency.Wallets.Count; j++)
						{
							McsUtility.Models.WalletsModel infoWallet = infoCurrency.Wallets[j];
							ListViewItem itemWallet = new ListViewItem(new string[] { walletCount.ToString(), infoCurrency.Remark, infoWallet.Address, infoWallet.Remark })
							{
								Tag = infoWallet
							};
							WalletList.Items.Add(itemWallet);
							walletCount++;
						}

						for (int j = 0; j < infoCurrency.OrePools.Count; j++)
						{
							McsUtility.Models.WalletsModel infoPool = infoCurrency.OrePools[j];
							ListViewItem itemPool = new ListViewItem(new string[] { poolCount.ToString(), infoCurrency.Remark, infoPool.Address, infoPool.Remark })
							{
								Tag = infoPool
							};
							PoolList.Items.Add(itemPool);
							poolCount++;
						}
					}
				}
			}
		}

		#endregion

		#region void AgentSendRefresh() 发送刷新请求。

		/// <summary>
		/// 发送刷新请求。
		/// </summary>
		private void AgentSendRefresh()
		{
			//发送数据
			if (this.Agent.IsStarted)
			{
				byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerGetCurrencysInfo, "");
				this.Agent.AgentSend(bytes);
			}
			else
			{
				if (MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
					Common.Utility.FormClose(this);
			}
		}

		#endregion

		#region void RefreshEventArgs(object sender, EventArgs e) 执行刷新的事件。

		/// <summary>
		/// 执行刷新的事件。
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void RefreshEventArgs(object sender, EventArgs e)
		{
			AgentSendRefresh();
		}

		#endregion
	}
}
